package com.mjk.common.web.getway.restful.interceptor.type.commons.impl;

import com.mjk.common.base.response.BeeResponse;
import com.mjk.common.tools.interceptor.InterceptorChain;
import com.mjk.common.tools.logger.BizLogger;
import com.mjk.common.util.MapUtils;
import com.mjk.common.util.RandomUtil;
import com.mjk.common.util.StrUtils;
import com.mjk.common.web.getway.constns.GetwayConsts;
import com.mjk.common.web.getway.restful.interceptor.GetWayInterceptorReq;
import com.mjk.common.web.getway.restful.interceptor.annotation.BeeGetWayInterceptor;
import com.mjk.common.web.getway.restful.interceptor.type.GetWayInterceptor;
import com.mjk.common.web.getway.restful.interceptor.type.GetWayInterceptorType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

/**
 * 文件上传
 *
 * @author mjk
 */
@BeeGetWayInterceptor(value = 2, interceptorType = {GetWayInterceptorType.ALL})
public class GetWayFileUploadInterceptor implements GetWayInterceptor {
	@Value("${service.url:#{null}}")
	private String SERVICE_URL;//必带参数效应版本号
    @Override
    public BeeResponse interceptor(GetWayInterceptorReq request,
                                   InterceptorChain<GetWayInterceptorReq, BeeResponse> next) {
        String protocol = MapUtils.getString(request.getRestfulParams(), GetwayConsts.PROTOCOL);
        if(GetWayInterceptorType.IMPORT.getProto().equals(protocol)){//如果是文件倒入則不需要進行判斷
            return next.proceed(request);
        }
        try {
            if (request.getRequest() instanceof StandardMultipartHttpServletRequest fileRequest) {
                if (CollectionUtils.isEmpty(fileRequest.getMultiFileMap())) {
                    return next.proceed(request);
                }
                HashMap<String, ArrayList<String>> fileParams = new HashMap<>();
                for (Entry<String, List<MultipartFile>> entry : fileRequest.getMultiFileMap().entrySet()) {
                	synchronized(this) {
	                    MultipartFile file = fileRequest.getFile(entry.getKey());
                        if(null != file) {
                            String fileName = file.getOriginalFilename();
                            String fileEnd;
                            if (null!=fileName && fileName.contains(".")) {
                                fileEnd = fileName.substring(fileName.lastIndexOf("."));
                            } else {
                                fileEnd = fileName;
                            }
                            String cName = RandomUtil.getShortUuid();
                            String filePath = request.getUploadPath() + cName + fileEnd;
                            String url = SERVICE_URL + cName + fileEnd;
                            //对于相同时间段里面 上传相同的文件名称 处理可能会出现问题，这里在文件名称后面加上一个时间戳用以区分
                            File f = new File(filePath);
                            file.transferTo(f);

                            String key1 = StrUtils.removeEndNum(entry.getKey());
                            ArrayList<String> urls = fileParams.get(key1);
                            if (CollectionUtils.isEmpty(urls)) {
                                urls = new ArrayList<>();
                                fileParams.put(key1, urls);
                            }
                            urls.add(url);
                        }
                	}
                }
                for (Entry<String, ArrayList<String>> entry : fileParams.entrySet()) {
                    request.getParams().put(entry.getKey(), StrUtils.join(entry.getValue(), ","));
                }
            } else {
                return next.proceed(request);
            }
        } catch (Exception e) {
            BizLogger.error(e);
        }
        return next.proceed(request);
    }


}
